﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using CommonLibrary.Logs;
using LitJson;

namespace CommonLibrary
{
    /// <summary>
    /// XML字符串转Json
    /// </summary>
    public class XmLtoJson
    {
        /// <summary>
        /// XML字符串转json字符串
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>

        public string ToJson(SortedDictionary<string, object> m_values)
        {

            string jsonStr = JsonMapper.ToJson(m_values);
            return jsonStr;

        }
        public SortedDictionary<string, object> FromXml(string xml)
        {
            SortedDictionary<string, object> m_values = new SortedDictionary<string, object>();
            if (string.IsNullOrEmpty(xml))
            {
                //Log.Error(this.GetType().ToString(), "将空的xml串转换为WxPayData不合法!");
                throw new Exception("将空的xml串转换为WxPayData不合法!");
            }
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml);
            XmlNode xmlNode = xmlDoc.FirstChild;//获取到根节点<xml>
            XmlNodeList nodes = xmlNode.ChildNodes;
            foreach (XmlNode xn in nodes)
            {
                XmlElement xe = (XmlElement)xn;
                m_values[xe.Name] = xe.InnerText;//获取xml的键值对到WxPayData内部的数据中
            }
            try
            {
                //2015-06-29 错误是没有签名
                if ((string) m_values["return_code"] != "SUCCESS")
                {
                    return m_values;
                }
                //CheckSign();//验证签名,不通过会抛异常
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return m_values;
        }
    }
}
